#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2023/12/11 22:23
# @Author  : 新猿异码
# @Site    : https://gitee.com/chshao/autotest
# @CSDN    : https://blog.csdn.net/m0_37576542?type=blog
# @File    : wecom.py
# @Desc    : 企业微信通知模块
# @Software: PyCharm
import os
import requests


class Wecom(object):

    def __init__(self):
        self._webhook = None
        self._headers = None

    @property
    def webhook(self):
        return self._webhook

    @webhook.setter
    def webhook(self, value):
        self._webhook = value

    @property
    def headers(self):
        return self._headers

    @headers.setter
    def headers(self, value):
        self._headers = value

    def send_message(self, subject, content, attach_files):
        """
        发送企业微信消息
        :param subject:
        :param content:
        :param attach_files:
        :return:
        """
        # markdown类型，需要传的参数
        data_content = {
            'msgtype': 'markdown',
            'markdown': {
                'content':
                    f'{subject}\n>'
                    f'{content}'
            }
        }
        if self.headers is None:
            self.headers = {"Content-Type": "application/json"}
        resp = requests.post(url=self.webhook, json=data_content, headers=self.headers)
        if resp.status_code != 200:
            print("消息发送失败！")
        upload_file_url = f"{self.webhook}&type=file"
        for file in attach_files:
            if os.path.exists(file):
                # 请求数据，是rb读取文件流，获取到media_id
                data = {"file": open(file, "rb")}
                res = requests.post(upload_file_url, files=data).json()
                media_id = res.get('media_id')

                # 发送文件类型报告消息
                data_content = {
                    "msgtype": "file",
                    "file": {
                        "media_id": media_id
                    }
                }
                resp = requests.post(url=upload_file_url, json=data_content, headers=self.headers)
                if resp.status_code != 200:
                    print("文件发送失败！")

